package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.User;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.UserService;
import com.zrrd.reggie.utils.SMSUtils;
import com.zrrd.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        String phone =user.getPhone();
        //生成验证码
        //使用工具类
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("生成的验证码======》"+code);
        //调用阿里云发送短信要花钱先不用
        //SMSUtils.sendMessage("ABC商城","SMS_463600053","13587551056","123456");
        //存入session
        //request.getSession().setAttribute(phone,code);
        //改造 将生成的验证码存入redis 并设置过期时间
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        //但是有许多人发，所以key不能固定，key为手机号就不会重复

        return R.success("发送成功");
    }
    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request){
        //获取参数
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //Object sessionCode = request.getSession().getAttribute(phone);
        //从redis中取
        Object o = redisTemplate.opsForValue().get(phone);
        log.info("登录获取的验证码是====》"+o);
        //加入双引号是为了变成字符串
        //sessionCode+"" 暂时给成123456暂时不要sessionCode != null &&
        if( code.equals("123456")){
            //验证成功
            QueryWrapper<User> wrapper =new QueryWrapper<>();
            wrapper.eq("phone",phone);
            User user = userService.getOne(wrapper);
            if (user == null){
                user =new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //返回用户信息
            //记得存一份到session
            request.getSession().setAttribute("user",user);
            redisTemplate.delete(phone);
            return R.success(user);

        }else {
            return R.error("验证码不正确");
        }

    }
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

}
